<template>
  <div class="menu-wrapper">
    <CategroyDialog ref="memberCategoryDialog" request="memberCategory" @confirm="dialogConfirm" />
    <office-dialog ref="officeDialog" @confirm="officeConfirm" />
    <el-form ref="MemberForm" :model="form" :rules="rules" label-width="120px">
      <div v-if="!memberType" style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">基本信息</span>
      </div>
      <div style="display: flex">
        <el-form-item label="账号" :prop="'member.mobile'" :rules="rules.mobile">
        <el-input v-model="form.member.mobile" type="Number" placeholder="请输入注册账号" style="width: 200px"   />
          </el-form-item>
        <el-form-item label="默认密码" >
          <span>123456</span>
        </el-form-item>
      </div>
      <div style="display: flex">
        <el-form-item label="姓名" :prop="'member.name'" :rules="rules.name">
          <el-input v-model="form.member.name" placeholder="请输入姓名" style="width: 200px" />
        </el-form-item>
        <el-form-item label="所属门店"  prop="member.shopId"  :rules="rules.shopId" >
          <el-select
            value-key="id"
            v-model="form.member.shopName"
            style="width: 200px"
            :filter-method="remoteShop"
            filterable
            placeholder="请选择"
            @change="shopselect">
            <el-option
              v-for="item in shoplist"
              :key="item.id"
              :label="item.name"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
        <div style="display: flex">
        <el-form-item label="等级" :prop="'member.vip'" :rules="rules.vip">
          <el-select v-model="form.member.vip" style="width: 200px" placeholder="请选择类型" @change="change">
            <el-option v-for="item in vips" :key="item.id" :label="item.name" :value="item.vip" />
          </el-select>
        </el-form-item>
<!--          <el-form-item label="员工类型" prop="paymentPluginId">-->
<!--            <el-select v-model="form.member.memberType" style="width: 200px" placeholder="请选择员工类型">-->
<!--              <el-option v-for="item in memberForm" :key="item.value" :label="item.name" :value="item.value" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        </div>
      <div style="display: flex">
        <el-form-item label="所在地" :prop="'member.areaName'" :rules="rules.areaName">
          <div style="display: flex; justify-content: space-between">
            <Distpicker :province="district.province" :city="district.city" :area="district.area" @selected="onSelected" style="width:450px" />
            <el-button  type="primary" style="height:36px; padding: 0 20px;margin-left: 10px"  @click="mapShowFn"><i class="el-icon-map-location" /></el-button>
          </div>
        </el-form-item>
      </div>
       <div style="display: flex">
          <div style="display: flex;">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="form.building" style="width: 520px" placeholder="道路、小区/楼/村，例：厦门市思明区龙山中路84号启达大厦" />
            </el-form-item>
          </div>
        </div>
        <!-- <el-form-item label="收货地址" prop="building"> -->
          <!-- <el-tooltip class="item" effect="dark" content="点击重新选择小区或楼宇" placement="top">
            <el-link v-show="form.building" type="primary" :underline="false" @click="mapShowFn">{{ form.building }}</el-link :underline="false">
          </el-tooltip> -->
        <!-- </el-form-item> -->
      <div style="display: flex;">
        <el-form-item label="门牌号" prop="roomNumber">
          <el-input v-model="form.roomNumber" style="width: 380px" placeholder="请输入门牌号，例：220室" />
        </el-form-item>
        <el-form-item label="楼层" prop="level" label-width="50px">
          <el-select v-model="form.level" style="width: 90px" placeholder="请选择">
            <el-option v-for="item in levelOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </div>
      <div v-if="!memberType" style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
        <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">详细信息</span>
      </div>
<!--      <div style="display: flex;">-->
<!--        <el-form-item label="会员有效期"  prop="member.vipExpired" v-if="!memberType" :rules="rules.vipExpired" >-->
<!--         <div class="memberValidity">-->
<!--           <el-date-picker-->
<!--             v-model="form.member.vipExpired"-->
<!--             type="date"-->
<!--             placeholder="选择日期"-->
<!--             format="yyyy 年 MM 月 dd 日"-->
<!--             value-format="yyyy-MM-dd"-->
<!--           >-->
<!--           </el-date-picker>-->
<!--         </div>-->
<!--        </el-form-item>-->
<!--      </div>-->
      <div>
        <el-form-item label="备用电话" v-if="!memberType" class="redItem">
          <el-input v-model="form.member.phone" style="width: 520px" placeholder="可填写多个联系电话,用&quot;,&quot;分割" />
        </el-form-item>
        <el-form-item label="员工备注" class="redItem">
          <el-input v-model="form.member.memo" style="width: 520px" placeholder="请填写员工备注" />
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item :label="optionsType" prop="paymentPluginId">
          <el-select v-model="form.member.paymentPluginId" style="width: 200px" placeholder="请选择付款方式">
            <el-option v-for="item in optionsForm" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      <el-form-item label="客户分类">
        <el-input v-model="memberCategoryName" style="width: 200px" suffix-icon="el-icon-arrow-down" placeholder="请选择客户分类" @focus="dialogShow" />
      </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item label="员工经理">
          <el-select
            v-model="salesmanName"
            style="width: 200px"
            :filter-method="remoteSalesman"
            value-key="id"
            filterable
            placeholder="请选择"
            @change="selectSalesman"
            @focus="memberFocus"
          >
            <el-option v-for="item in salesmanList" :key="item.id" :label="item.name" :value="item" />
            <el-option key="-" style="background-color: #DCDFE6;text-align: center;" label="底部隐藏块" value="-" />
            <el-option key="/" style="background-color: #909399;color:white ;text-align: center;position: absolute;bottom:0;width: 100%" label="--- 搜索客户 ---" value="/" />
          </el-select>
        </el-form-item>
        <el-form-item label="推荐人" prop="officeName">
          <el-select
            v-model="memberName"
            style="width: 200px"
            :filter-method="remoteMethod"
            value-key="id"
            filterable
            placeholder="请选择"
            @change="selectMember"
            @focus="memberFocus"
          >
            <el-option v-for="item in memberList" :key="item.id" :label="item.name" :value="item" />
            <el-option key="-" style="background-color: #DCDFE6;text-align: center;" label="底部隐藏块" value="-" />
            <el-option key="/" style="background-color: #909399;color:white ;text-align: center;position: absolute;bottom:0;width: 100%" label="--- 搜索客户 ---" value="/" />
          </el-select>
        </el-form-item>
      </div>
      <div style="display: flex;" v-if="!memberType">
        <el-form-item label="电子邮箱">
          <el-input v-model="form.member.email" style="width: 200px" placeholder="请填写电子邮箱" />
        </el-form-item>
        <el-form-item label="纳税识别号" prop="taxNum">
          <el-input v-model="form.taxNum" style="width: 200px" />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" :loading="clicked" @click="saveMember('MemberForm')">完 成</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="位置信息" :visible.sync="mapShow" top="5vh" width="800px" append-to-body>
      <Map :initcenter="[form.lng, form.lat]" @getMap="getMap" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapShow = false">取 消</el-button>
        <el-button type="primary" @click="savelngLat">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      title="双击选择客户"
      :visible.sync="memberTableVisible"
      width="950px"
      append-to-body
      :before-close="memberTableClose"
    >
      <div style="position: relative">
        <member-table @memberDouble="memberDouble" @addMemberClick="addMemberClick" @memberTableClose="memberTableClose" />
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      title="双击选择客户经理"
      :visible.sync="salesmanType"
      width="950px"
      append-to-body
      :before-close="salesmanTableClose"
    >
      <div style="position: relative">
        <sysEmployeeTable @sysEmployeeDouble="sysEmployeeDouble"/>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
  /deep/.el-icon-map-location:before {
    font-size: 20px;
  }
  .redItem >>> .el-form-item__label{
    color: red;
  }
  .menu-wrapper {
    margin: 15px;
  }
  .memberValidity .el-date-editor{
    width: 200px!important;
  }

</style>
<script>
import Distpicker from '@/components/Distpicker/Distpicker'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { list as memberList } from '@/api/member'
import { list } from '../../api/vip'
import { list as companys } from '../../api/company'
import { EventBus } from '@/api/eventBus'
import OfficeDialog from '@/components/OfficeDialog'
import utils from '../../utils/utils.js'
import { save } from '@/api/member'
import CategroyDialog from '@/components/CategoryDialog'
import Map from '@/components/GaodeMap/index'
import MemberTable from '@/components/MemberTable/index'
import sysEmployeeTable from '@/components/sysEmployeeTable/index'
import {list as shoplist,} from '@/api/shop'
import {list as sysEmployeeList} from '@/api/sysEmployee'
import {mapGetters} from 'vuex'
import {IPLocation} from '@/api/mapLine'

export default {
  name: 'member-add',
  filters: {},
  directives: { elDragDialog },
  components: { CategroyDialog, OfficeDialog, Map, MemberTable,Distpicker,sysEmployeeTable},
  props: [
    'memberType',
    'clickPhone',
  ],
     computed: {
      ...mapGetters([
        'employee',
      ])
    },
  data() {
    return {
      shippingDate:"",
      // district: {},
      shoplist:[],//所属门店列表
      isMemberName:'',
      isSalesmanName:'',
      memberName:'',
      memberList: [],
      salesmanList:[],//业务员
      salesmanName:'',
      salesmanType:false,
      officeName: '',
      callType:'',
      memberId: '',
      managerId:'',
      vips: [],
      clicked: false, // 按钮防双击
      mapShow: false,
      tempLng: '',
      tempLat: '',
      tempAddress: '',
      tempAreaId: '',
      tempAois: '',
      memberTableVisible: false,
      tempAreaName: '',
      form: {
        address: '',
        building: '',
        consignee: '',
        isDefault: true,
        taxNum:'',
        lat: '',
        lng: '',
        level: 0,
        phone: '',
        roomNumber: '',
        member: {
          vipExpired:'',
          address: '',
          areaId: '',
          code:'',
          areaName: '',
          promoterId: '',
          companyId: '',
          officeId: '',
          mobile: '',
          gender:'0',
          email: '',
          // paymentPluginId:'cashPayPlugin',
          paymentPluginId:'debtPayPlugin',
          vip: 0,
          memberCategoryId: '',
          // memberType: '0',
          memberType: '1',
          shopId:'',
          shopName:null,//所属门店名s
          memo:null,
          managerId:''
        }
      },
      district:{},
      // district: { province: 440000, city: '广州市', area: '海珠区' },
      companyList: [],
      vipName: '',
      memberCategoryName: '',
      dateName: '出生日期',
      optionsType: '付款方式',
       levelOptions: [
         { label: '有电梯', value: 0 },
         { label: '一层楼', value: 1 },
         { label: '二层楼', value: 2 },
         { label: '三层楼', value: 3 },
         { label: '四层楼', value: 4 },
         { label: '五层楼', value: 5 },
         { label: '六层楼', value: 6 },
         { label: '七层楼', value: 7 },
         { label: '八层楼', value: 8 },
         { label: '九层楼', value: 9 }
       ],
      optionsForm: [
        { name: '月结', value: 'debtPayPlugin'},
        { name: '现结', value: 'cashPayPlugin' },
        { name: '代销', value: 'salePayPlugin'},
      ],

      memberForm: [
        { name: '企业客户', value: '1'},
        // { name: '个人员工', value: '0' },
        // { name: '批发员工', value: '2'},
      ],
      rules: {
        name: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入注册手机', trigger: 'blur' }
        ],
        vip: [
          { required: true, message: '请选择员工等级', trigger: 'blur' }
        ],
        consignee: [
          { required: true, message: '请输入收货人名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
         building: [
           { required: true, message: '请输入详细地址', trigger: 'blur' }
         ],
//        address:[
//          { required: true, message: '请输入详细地址', trigger: 'blur' }
//        ],
        roomNumber: [
          { required: true, message: '请输入门牌号', trigger: 'blur' }
        ],
        shopId: [
          { required: true, message: '请选择所属门店', trigger: 'blur' }
        ],
        areaName: [
          { required: true, message: '请选择所在地', trigger: 'blur' }
        ],
        // level: [
        //   { required: true, message: '请选择楼层', trigger: 'blur' }
        // ]
      }
    }
  },
  created() {

    console.log(this.$store,"$store$store$store$store")

    if (this.$route.query.type!=undefined||this.$route.query.type!=''||this.$route.query.type!=null){
      this.callType=this.$route.query.type
    }
    if (this.clickPhone!=''||this.clickPhone!=undefined||this.clickPhone!=null){
        this.form.member.mobile=this.clickPhone
    }

    this.loadCompany('')
    this.loadMember('')
    this.loadVip()
    this.mapIPLocation()
    this.shoplistshow()
    this.loadShopClick('')
    this.loadSalesman('')
    if(this.employee !=null&&this.employee.shopId!=null&&this.employee.shopId!=undefined){
        this.form.member.shopId=this.employee.shopId
        this.form.member.shopName=this.employee.shopName
    }
  },
  methods: {
    // onSelected(val) {
    //     console.log(val)
    //     if (!utils.isNull(val.city) && !utils.isNull(val.area) && !utils.isNull(val.area.code)) {
    //       this.form.areaId = val.area.code
    //       this.form.areaName = val.province.value + val.city.value + val.area.value
    //       // this.form.areaName = val.area.value
    //     }
    //   },
    cleard(){
            //this.form.member.name=''
      this.form.member.code=''
      this.salesmanName=''
      this.form.member.managerId = ''
      this.form.building=''
      this.form.roomNumber=''
      this.memberCategoryName=""
      this.form.member.memberCategoryId = ""
      this.form.taxNum=''
      this.form.member.memo=''
    },
     shopselect(val){
        this.form.member.shopId=val.id
        this.form.member.shopName=val.name

      },
     shoplistshow(){
        shoplist().then(res=>{
          this.shoplist=res.data.data
        })
      },
    loadShopClick(query){
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      shoplist(params).then(response => {
        console.log(response)
        _this.shoplist = response.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    remoteShop(query){
      this.loadShopClick(query)
    },
    mapShowFn() {
      this.mapShow = !this.mapShow
    },
    getMap(lng, lat, addressData) {
      // console.log(lng, lat, addressData)
      // 定义变量保存经纬度和地址
      this.tempLng = lng
      this.tempLat = lat
      this.tempAreaId = addressData.addressComponent.adcode
      this.tempAois = addressData.formattedAddress
      this.tempAreaName = `${addressData.addressComponent.province}${addressData.addressComponent.city}${addressData.addressComponent.district}`
    },
    memberFocus() {
      if (this.form.member.promoterId != null || this.form.member.promoterId != '') {
        this.isMemberName=this.memberName
        this.memberId = this.form.member.promoterId
      }

    },
    selectMember(data) {
      var _this = this
      if (data == '/') {
        _this.form.member.promoterId = ''
        _this.memberTableVisible = true
      } else {
        _this.memberName=data.name
        _this.form.member.promoterId = data.id
      }
    },
    addMemberClick(val) {
      val.forEach(item => {
        this.form.member.promoterId = item.id
        this.memberName=item.name
      })
    },
    memberDouble(data) {
      this.form.member.promoterId = data.id
      this.memberName=data.name
      this.memberTableVisible = false
    },
    memberTableClose() {
      this.form.member.promoterId = this.memberId
      this.memberName=this.isMemberName
      this.memberTableVisible = false
    },
    savelngLat() {
      this.form.lng = this.tempLng
      this.form.lat = this.tempLat
      // this.form.address = this.tempAddress
      this.form.building = this.tempAois
      this.form.member.areaId = this.tempAreaId
      this.form.member.areaName = this.tempAreaName
      console.log(this.tempAreaName,'kughfiuehiure')
      this.form.member.address = this.form.building
      const reg = /.+?(省|市|自治区|自治州|县|区)/g
      this.district.province = this.form.member.areaName.match(reg)[0]
      this.district.city = this.form.member.areaName.match(reg)[1]
      this.district.area = this.form.member.areaName.match(reg)[2]
      this.mapShowFn()
      console.log(this.form.member.areaName);

    },

    mapIPLocation(){
      var _this = this;
      IPLocation().then(res=>{
        console.log(res,'efweiufgw')
        _this.district = {}
        const reg = /.+?(省|市|自治区|自治州|县|区)/g
        _this.district.province = res.data.address.match(reg)[0]
        _this.district.city =res.data.address.match(reg)[1]
        _this.district.area = res.data.address.match(reg)[2]
      })
    },
    // 会员选择
    loadMember(query) {
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      memberList(params).then(response => {
        _this.memberList = response.data.data
      }).catch(error => {
      })
    },
    change(e) {
      console.log(e)
    },
    remoteMethod(query) {
      this.loadMember(query)
    },
    productMethod(query) {
      this.loadCompany(query)
    },
    officeConfirm(val) {
      this.form.member.officeId = val.id
      this.officeName = val.name
    },
    officeShow() {
      console.log('点击了')
      this.$refs.officeDialog.show()
    },
    loadVip() {
      list().then(res => {
        this.vips = res.data.data
      })
    },
    loadCompany(query) {
      companys({ name: query }).then(res => {
        this.companyList = res.data.data
      })
    },

    onSelected(val) {
      if (!utils.isNull(val.area) && !utils.isNull(val.area.code)) {
        this.form.member.areaId = val.area.code
        this.form.member.areaName = val.province.value+val.city.value+val.area.value
      }else if (!utils.isNull(val.city) && !utils.isNull(val.city.code)){
        this.form.member.areaId = val.city.code
        this.form.member.areaName = val.province.value+val.city.value

      }else if (!utils.isNull(val.province) && !utils.isNull(val.province.code)){
        this.form.member.areaId = val.province.code
        this.form.member.areaName = val.province.value
      }
      // console.log(this.form.member.areaName);
    },
    dialogShow() {
      console.log('点击了')
      this.$refs.memberCategoryDialog.show()
    },
    dialogConfirm(val) {
      console.log(val)
      this.memberCategoryName = val.name
      this.form.member.memberCategoryId = val.id
    },
    saveMember(form) {
      console.log(this.$route.query.companyId)
      this.$refs[form].validate((valid) => {
        if (valid) { // 校验表单
          this.clicked = true
          this.form.address = this.form.building + this.form.roomNumber
          const params = new URLSearchParams()

          params.append('companyId ', this.$route.query.companyId)
          params.append('address', this.form.address)
          params.append('building', this.form.building)
          params.append('consignee', this.form.member.name)
          params.append('isDefault', this.form.isDefault)
          if (utils.isNull(this.form.level)) {
            this.form.level = 0;
          }
          params.append('level', this.form.level)
          params.append('lat', this.form.lat)
          params.append('lng', this.form.lng)
          // params.append('level', this.form.level)
          if (utils.isNull(this.form.phone)) {
            params.append('phone', this.form.member.mobile)
          } else {
            params.append('phone', this.form.phone)
          }
          params.append('roomNumber', this.form.roomNumber)
          params.append('vipExpired', this.form.vipExpired)
          if(this.$route.query.companyId != null){
            this.form.member.companyId = this.$route.query.companyId
          }
          save(params, this.form.member).then(response => {
            this.clicked = false
            if (response.type == 'success') {
              this.$router.push({
                path: "/company/employeeList",
                query: { id: this.$route.query.companyId , companyName: this.$route.query.companyName }
              });
            } else {
              this.$message({
                message: response.content,
                offset: 120,
                center: true
              })
            }
          }).catch(() => {
            this.clicked = false
          })
        } else {
          return false
        }
      })
    },
    // 员工经理
    loadSalesman(query){
      var _this = this
      const params = new URLSearchParams()
      params.append('name', query)
      sysEmployeeList(params).then(response => {
        console.log(response)
        _this.salesmanList = response.data.data
      }).catch(error => {
        console.log(error)
      })
    },
    remoteSalesman(query){
      this.loadSalesman(query)
    },
    selectSalesman(data){
      var _this = this
      if (data == '/') {
        _this.form.member.managerId = ''
        _this.salesmanType = true
      } else {
        _this.salesmanName=data.name
        _this.form.member.managerId = data.id
      }
    },
    // memberFocus() {
    //   if (this.form.member.managerId != null || this.form.member.managerId != '') {
    //     this.isSalesmanName=this.salesmanName
    //     this.managerId = this.form.member.managerId
    //   }
    // },
    // 员工经理弹窗
    salesmanTableClose() {
      this.form.member.managerId = this.managerId
      this.salesmanName=this.isSalesmanName
      this.salesmanType = false
    },
    sysEmployeeDouble(data) {
      this.form.member.managerId = data.id
      this.salesmanName=data.name
      this.salesmanType = false
    },
  }
}
</script>
